from django.db.models import Q
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView

from schoolBook import models
from schoolBook.utils.excelSave import loadfile
from schoolBook.utils.searlizerBook  import Base_Searlizer
from schoolBook.utils.tengxun_bookapi.bookAPI import getBookInfo
from shareAPI.utils import JWTencode
from shareAPI.views import APIResponse

import logging

class Login(APIView):
    authentication_classes = []
    def get(self,request,*args,**kwargs):

        # username = request.query_params.get('username')
        # password = request.query_params.get('password')

        return APIResponse(0,msg='GEt请求成功')
        # return JsonResponse(dataJson)

    def post(self,request,*args,**kwargs):
        logging.info(request.data)
        username = request.data.get('username')
        password = request.data.get('password')
        print(username, password)

        userObj = models.MS_COLLEGE.objects.filter(USERNAME=username, PASSWORD=password).first()
        if not userObj:
            return APIResponse(0,msg="用户名或密码错误",code=201)
        token = JWTencode.createToken({'user_id': userObj.ID, 'username': username}, 1000)

        # return HttpResponse('我是django后台，post请求成功',f'{username},{password}')
        # return JsonResponse({"code":1000,"data":[token]},safe=False)
        return APIResponse({'code':200,"token":token},msg="登录成功")


class Book(APIView):
    # authentication_classes = []
    def get(self,request,*args,**kwargs):
        '''根据用户识别学校，获取该学校的资源'''
        username = request.user['username']
        logging.info(username)
        querySet = models.MS_BookLibrary.objects.filter(BOOK_School__USERNAME=username).all()  # 登录用户是否是学生会
        if querySet:
            logging.info("会员登录")
        else:
            return APIResponse(0, msg='会员不在数据库内')

        serResult = Base_Searlizer.B_MS_BookLibrary_serializers(querySet,many=True)
        return APIResponse(serResult.data)
        # print(len(querySet))
        # return APIResponse(0, msg=len(querySet))

    def post(self,request,*args,**kwargs): #增加一条
        username = request.user['username']
        isbn = request.data.get('isbn')
        querySet = models.MS_COLLEGE.objects.filter(Q(USERNAME=username)).first()  # 登录用户查询集

        if querySet.hasTimes <=0:
            return APIResponse(0, msg="您的使用次数不够了，请加微信：317909531咨询，由于调用的收费api，所以会产生一定的费用")
        # 获取到线程
        if isbn[0:2]!='97':
            return APIResponse(0,msg="不支持该书号值，仅支持97开头isbn")

        # 书库里边如果有这本书，就更新多对多关系，否则就进行录入 if querySet_ISBN
        # 书库里有这本书，但是这个学校没有录入过这本书，就需要作出不同的响应if querySet_IsbnAndCollege
        querySet_ISBN =  models.MS_BookLibrary.objects.filter(Q(isbn=isbn)).first()  # 登录用户查询集
        if querySet_ISBN: #如果存在，不在查询api，直接添加进数据库关系
            querySet_IsbnAndCollege = models.MS_BookLibrary.objects.filter(Q(isbn=isbn)&Q(BOOK_School__USERNAME=username)).first()
            if querySet_IsbnAndCollege:# 如果学校有这本书，就不操作提醒前端
                return APIResponse(0, msg="本校已经录入过这本书，本次操作不会扣减次数")
            #否则就进行新增
            querySet_ISBN.BOOK_School.add(querySet)  #加入对应的关系
            querySet.hasTimes = querySet.hasTimes-1  #更新次数字段
            querySet.save()  #更新次数字段
            return APIResponse(0,msg="success")
        #查询书号内容api调用
        bookDict = getBookInfo(isbn)
        querySet.hasTimes = querySet.hasTimes - 1  # 更新次数字段
        querySet.save()  # 更新次数字段
        #序列化录入
        bookDict['BOOK_School'] = [querySet.pk]
        print(bookDict)


        serResult = Base_Searlizer.B_MS_BookLibrary_serializers(data=bookDict)
        if serResult.is_valid() == False:  # 如果校验失败，会直接抛异常，返回给前台
            logging.info(serResult.errors)

            return APIResponse(serResult.errors, msg='存储失败')
        # print(serResult.validated_data)
        # print(repr(serResult))
        obj = serResult.save()  # 返回一个数据库对象实例

        return APIResponse(result=serResult.data, msg=f"存储成功")

    # def post(self, request, *args, **kwargs):  # 增加一条
    #     username = request.user['username']
    #     querySet = models.MS_COLLEGE.objects.filter(Q(USERNAME=username)).first()  # 登录用户是否是学生会
    #     if querySet:
    #         print("会员登录")
    #     else:
    #         return APIResponse(0, msg='会员不在数据库内')
    #     request.data['BOOK_School'] = [querySet.pk]
    #     print(request.data)
    #
    #     # return APIResponse(0)
    #     serResult = Base_Searlizer.B_MS_BookLibrary_serializers(data=request.data)
    #     if serResult.is_valid() == False:  # 如果校验失败，会直接抛异常，返回给前台
    #         return APIResponse(serResult.errors, msg='fail')
    #     print(serResult.validated_data)
    #     print(repr(serResult))
    #     obj = serResult.save()  # 返回一个数据库对象实例
    #     return APIResponse(result=serResult.data, msg=f"success")

    def put(self,request,*args,**kwargs):
        return APIResponse(0)



class GetExcel(APIView):
    # authentication_classes = []
    def get(self,request):
        username = request.user['username']

        schoolname = models.MS_COLLEGE.objects.filter(USERNAME=username).first().SchoolName
        print(schoolname)
        filename = loadfile(username,schoolname)

        return APIResponse({'url':filename},msg='请自行保存')